﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace BGSpaceShooterServer
{
    public partial class ServerControl : Form
    {
        private Server server;

        private delegate void UpdateListbox(string msg);

        public ServerControl()
        {
            InitializeComponent();

            server = new Server();

            server.MessageAppeared += new LogEventHandler(serverMessageAppeared);

            string[] ips = server.GetCurrentIPs();

            listBox1.Items.Clear();

            listBox1.Items.AddRange(ips);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int port;
            if(Int32.TryParse(textBox1.Text, out port))
            {
                server.InitializeGame(Convert.ToInt32(numericUpDown1.Value), port);
            }
        }

        void serverMessageAppeared(object obj, LogEventArgs logEventArgs)
        {
            //richTextBox1.AppendText(logEventArgs.LogMessage + "\n");
            ThreadSafeRTBUpdater rtbUpdater = new ThreadSafeRTBUpdater(this.richTextBox1);
            rtbUpdater.UpdateRTB(logEventArgs.LogMessage);

        }

        private void ServerControl_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (server != null)
            {
                server.EndGame();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (server != null)
            {
                server.StartGame();
            }
        }

        private void ServerControl_Load(object sender, EventArgs e)
        {
            //Autostart :D
            button1_Click(sender, e);
        }

    

        


    }
}
